package com.yunfeng.supercall.fragment;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.lin.utils.SharePreferenceUtil;
import com.ly.quickdev.library.utils.IDCard;
import com.ly.quickdev.library.utils.ImageTools;
import com.ly.quickdev.library.utils.ImageTools.OnBitmapCreateListener;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.activity.RegActivity.ParamsGenerator;
import com.yunfeng.supercall.activity.LoginActivity;
import com.yunfeng.supercall.activity.RegStep3Activity;
import com.yunfeng.supercall.activity.RegStepFirstPersonalActivity;
import com.yunfeng.supercall.app.AppContext;
import com.yunfeng.supercall.httputils.HttpClient;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.httputils.UploadUtilsAsyncTask;
import com.yunfeng.supercall.httputils.UploadUtilsAsyncTask.OnUplaodListener;

public class RegStep2PersonalFragment extends Fragment implements
ParamsGenerator, OnClickListener {

	private ImageTools mImageTools;
	private Bitmap mBitmap;
	private ImageView mImageView;
	private RadioGroup mRadioGroup;
	private Button mButtonClick;
	
	View mView;
	private EditText mEditTextSign;
	private EditText mEditTextOftenName;
	private EditText mEditTextRealName;
	private EditText mEditTextIdCard;
	private EditText mEditTextAddress;
	private EditText mEditTextPwd;
	HttpClient mHttpClient = new HttpClient();
	private String phone;
	private FrameLayout frameLayoutBack;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mImageTools = new ImageTools(this);
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mView = inflater.inflate(R.layout.fragment_reg_step2_personal, null);
		
		
	frameLayoutBack = (FrameLayout) mView.findViewById(R.id.framelayout_back);
		
		frameLayoutBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getActivity().finish();
			}
		});
		
		mImageView = (ImageView) mView.findViewById(R.id.avatar);
		mButtonClick = (Button)mView.findViewById(R.id.button_click);
		mEditTextSign = (EditText) mView.findViewById(R.id.sign);
		mEditTextOftenName = (EditText) mView.findViewById(R.id.often_name);
		mEditTextRealName = (EditText) mView.findViewById(R.id.real_name);
		mEditTextIdCard = (EditText) mView.findViewById(R.id.id_card);
		mEditTextAddress = (EditText) mView.findViewById(R.id.addr);
		mEditTextPwd = (EditText) mView.findViewById(R.id.edittext);
		
		Bundle bundle = getArguments();
		phone = bundle.getString("data");
		
		mButtonClick.setOnClickListener(this);
		mImageView.setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						mImageTools.showGetImageDialog("选择图片的方式");
					}
				});
		mRadioGroup = (RadioGroup) mView.findViewById(R.id.radio);
		return mView;
	}




	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		generateParams();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case ImageTools.CAMARA:
				mImageTools.getBitmapFromCamara(new OnBitmapCreateListener() {

					@Override
					public void onBitmapCreate(Bitmap bitmap, String path) {
						// TODO Auto-generated method stub
						mImageTools.startZoomPhoto(
								Uri.fromFile(new File(path)), 160, 160);
					}
				});
				break;
			case ImageTools.GALLERY:
				mImageTools.startZoomPhoto(data.getData(), 160, 160);
				break;
			case ImageTools.BITMAP:
				mBitmap = mImageTools.getBitmapFromZoomPhoto(data);
				mImageView.setImageBitmap(mBitmap);
				break;
			}
		}
	}

	public JSONObject generateParams() {
		if (mBitmap == null) {
			mBitmap = AppContext.BITMAP;
			// showToast("请选择一个头像");
			// return null;
		}
		final String sign = mEditTextSign.getText().toString();
		final String oftenName = mEditTextOftenName.getText().toString();
		final String realName = mEditTextRealName.getText().toString();
		final String idCard = mEditTextIdCard.getText().toString();
		if (TextUtils.isEmpty(oftenName)) {
			Toast.makeText(getActivity(), "请输入常用名", Toast.LENGTH_LONG).show();
			return null;
		}
		if (!TextUtils.isEmpty(idCard)) {
			if (!new IDCard().verify(idCard)) {
				Toast.makeText(getActivity(), "请输入正确的身份证号码", Toast.LENGTH_LONG).show();
				return null;
			}
		}

		if (oftenName != null && oftenName.length() > 22) {
			Toast.makeText(getActivity(), "您输入的常用名太长了", Toast.LENGTH_LONG).show();
			return null;
		}
	/*	if (realName != null && realName.length() > 22) {
			Toast.makeText(getActivity(), "您输入的真实姓名太长了", Toast.LENGTH_LONG).show();
			return null;
		}*/
	/*	if (sign != null && sign.length() > 100) {
			Toast.makeText(getActivity(), "您输入的个人签名太长了", Toast.LENGTH_LONG).show();
			return null;
		}*/

		File myCaptureFile = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/.super/");
		if (!myCaptureFile.exists()) {
			myCaptureFile.mkdirs();
		}
		myCaptureFile = new File(myCaptureFile.getAbsolutePath() + "/"
				+ System.currentTimeMillis() + ".jpeg");
		BufferedOutputStream bos;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

//		showProgressDialog("正在上传头像...");
		UploadUtilsAsyncTask mUploadUtils = new UploadUtilsAsyncTask(new OnUplaodListener() {

			@Override
			public void onUploadSuccess(String data) {
				// TODO Auto-generated method stub
//				cancelProgressDialog();
				String pass = mEditTextPwd.getText().toString();
				JSONObject json = new JSONObject();
				int id = mRadioGroup.getCheckedRadioButtonId();
				if (id == R.id.rb1) {
					id = 1;
				} else {
					id = 2;
				}
				String addr = mEditTextAddress.getText().toString();

				try {
					json.put("i_nick_name", oftenName);
					json.put("i_real_name", "超号");
					json.put("i_card", "超号");
					json.put("i_sex", id);
					json.put("i_address", addr);
					
					json.put("i_note", "超号");
					json.put("i_type", 1);
					json.put("i_tel", phone);
					json.put("i_phone", phone);
					json.put("i_void", 0);
					json.put("i_vopass", 0);
					json.put("i_lat", 0);
					json.put("i_lng", 0);
					json.put("i_photo", data);
					json.put("i_pass", pass);
					Log.i("tag", json.toString());
					register(json);
//					startActivity(new Intent(getActivity(),
//							RegStepFirstActivity.class).putExtra("data",
//									json.toString()));
					// .putExtra("data", json.toString()));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onUploadError(String error) {
				// TODO Auto-generated method stub
/*				cancelProgressDialog();
				showToast(error);*/
			}

			@Override
			public void onUpload(long current, long total, long progress) {
				// TODO Auto-generated method stub

			}
		});
		mUploadUtils.execute(myCaptureFile.getAbsolutePath(),
				HttpClient.UPLOAD_IMG_URL);
		return null;

	}

	public void emptyParams() {
		JSONObject json = new JSONObject();

		try {
			json.put("i_nick_name", "");
			json.put("i_real_name", "");
			json.put("i_card", "");
			json.put("i_sex", 1);
			json.put("i_address", "");
			json.put("i_note", "");
			json.put("i_type", 1);
			json.put("i_tel", phone);
			json.put("i_void", 0);
			json.put("i_vopass", 0);
			json.put("i_lat", 0);
			json.put("i_lng", 0);
			json.put("i_photo", "");
			json.put("i_pass", "");

			startActivity(new Intent(getActivity(), RegStepFirstPersonalActivity.class)
			.putExtra("data", json.toString()));
			getActivity().finish();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void register(JSONObject json) {
		try {
			AjaxParams mAjaxParams = new AjaxParams();
			Iterator<String> iterator = json.keys();
			while (iterator.hasNext()) {
				String key = iterator.next();
				mAjaxParams.put(key, json.get(key) + "");
				
			}
//			showProgressDialog("正在注册...");
			mHttpClient.post("UserRegister", mAjaxParams, new MyAjaxCallBack() {

				@Override
				public void onReceiveError(String msg, String errorCode) {
					// TODO Auto-generated method stub
					try {
						
					Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
					Log.i("tag", "fail" + msg);
//					showToast(msg);
					} catch(NullPointerException e) {
						
					}
//					cancelProgressDialog();
				}

				@Override
				public void onReceiveData(String data, String msg) {
					// TODO Auto-generated method stub
					Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_LONG).show();
//					showToast("注册成功");
//					cancelProgressDialog();
					
					/*SharePreferenceUtil.getInstance().getUserName(getActivity());
					SharePreferenceUtil.getInstance().getPassword(getActivity());*/
					String pass = mEditTextPwd.getText().toString();
					SharePreferenceUtil.getInstance().updateUserInfo(getActivity(), phone, pass);
					
					startActivity(new Intent(getActivity(),
							LoginActivity.class)
					.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
							| Intent.FLAG_ACTIVITY_CLEAR_TASK));
					getActivity().finish();
				}
			});
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
